from django_redis import get_redis_connection
from rest_framework import serializers


class SmsCodeSerializer(serializers.Serializer):
    text = serializers.CharField(max_length=4, min_length=4, label="图片验证码")
    image_code_id = serializers.UUIDField(label="验证码编号")

    # 多字段校验
    def validate(self, attrs):
        # 获取图片验证码  跟image_code_id
        text = attrs.get("text")
        image_code_id = attrs.get("image_code_id")

        # 获取reids对象
        redis_connection = get_redis_connection("code")
        # 获取image_code_id
        redis_image_code = redis_connection.get("image_code_%s" % image_code_id)

        # 删除redis的图片验证码
        redis_connection.delete("image_code_%s" % image_code_id)

        # 判断图片验证码是否过期
        if not redis_image_code:
            raise serializers.ValidationError('图片验证码失效')
        # 判断用户输入的图片验证码是否正确
        if redis_image_code.decode().lower() != text.lower():
            raise serializers.ValidationError("验证码错误")

        return attrs
